package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.model.ProductComputeVO;
import com.ytjj.qmyx.supplychain.common.model.request.SalesStatisticalRequest;
import com.ytjj.qmyx.supplychain.common.model.response.ProductSalesDataResponse;
import com.ytjj.qmyx.supplychain.common.model.response.ProductSalesStatisticalResponse;
import com.ytjj.qmyx.supplychain.common.model.response.TopCategorySalesStatisticalResponse;
import com.ytjj.qmyx.supplychain.mapper.BankerMapper;
import com.ytjj.qmyx.supplychain.mapper.OrdersMapper;
import com.ytjj.qmyx.supplychain.mapper.ReturnGoodsMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductStatisticalService {

    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    @Resource
    private BankerMapper bankerMapper;

    public CommonResult getHead() {
        //今日销量（个）/销售金额（元）
        ProductComputeVO todayOrder = ordersMapper.getProductSalesByToday();
        //昨日销量（个）/销售金额（元）
        ProductComputeVO yesterdayOrder = ordersMapper.getProductSalesByYesterday();
        //今日售后订单（个）
        ProductComputeVO todayReturn = returnGoodsMapper.getReturnNumByToday();
        //昨日售后订单（个）
        ProductComputeVO yesterdayReturn = returnGoodsMapper.getReturnNumByYesterday();
        //总订单数
        ProductComputeVO countOrder = ordersMapper.getOrderCount();
        //总售后成功数
        ProductComputeVO countReturnSuccess = returnGoodsMapper.getCountReturnSuccess();
        //总订单数
        ProductComputeVO countOrderYesterday = ordersMapper.getOrderCountYesterday();
        //总售后成功数
        ProductComputeVO countReturnSuccessYesterday = returnGoodsMapper.getCountReturnSuccessYesterday();

        //销量比例
        BigDecimal volumePercent = (BigDecimal.ZERO != yesterdayOrder.getNumber() ? ((todayOrder.getNumber().subtract(yesterdayOrder.getNumber())).divide(yesterdayOrder.getNumber(), 2, RoundingMode.HALF_UP)) : todayOrder.getNumber()).multiply(BigDecimal.valueOf(100));
        //金额比例
        BigDecimal moneyPercent = BigDecimal.ZERO.compareTo(yesterdayOrder.getMoney()) != 0 ? (todayOrder.getMoney().subtract(yesterdayOrder.getMoney()).divide(yesterdayOrder.getMoney(), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100))) : (todayOrder.getMoney().setScale(2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)));
        //售后比例
        BigDecimal returnPercent = (BigDecimal.ZERO != yesterdayReturn.getNumber() ? (todayReturn.getNumber().subtract(yesterdayReturn.getNumber()).divide(yesterdayReturn.getNumber(), 2, RoundingMode.HALF_UP)) : todayReturn.getNumber()).multiply(BigDecimal.valueOf(100));
        //今日售后占订单比例
        BigDecimal returnRate = (BigDecimal.ZERO != countOrder.getNumber() ? (countReturnSuccess.getNumber().divide(countOrder.getNumber(), 4, RoundingMode.HALF_UP)) : BigDecimal.ZERO).multiply(BigDecimal.valueOf(100));
        //昨日售后占订单比例
        BigDecimal returnRateYesterday = (BigDecimal.ZERO != countOrderYesterday.getNumber() ? (countReturnSuccessYesterday.getNumber().divide(countOrderYesterday.getNumber(), 2, RoundingMode.HALF_UP)) : BigDecimal.ZERO).multiply(BigDecimal.valueOf(100));

        ProductSalesDataResponse productSalesDataResponse = ProductSalesDataResponse.builder()
                .productVolume(String.valueOf(todayOrder.getNumber().setScale(0, RoundingMode.HALF_UP)))
                .volumePercent(volumePercent.setScale(0, RoundingMode.HALF_UP).abs() + "%")
                .volumeFlag(todayOrder.getNumber().compareTo(yesterdayOrder.getNumber()) > 0 ? "up" : "down")
                .saleMoney(todayOrder.getMoney().toString())
                .moneyPercent((moneyPercent.setScale(0, RoundingMode.HALF_UP)).abs() + "%")
                .moneyFlag(todayOrder.getMoney().compareTo(yesterdayOrder.getMoney()) > 0 ? "up" : "down")
                .returnNum(String.valueOf(todayReturn.getNumber().setScale(0, RoundingMode.HALF_UP)))
                .returnPercent((returnPercent.setScale(0, RoundingMode.HALF_UP)).abs() + "%")
                .returnFlag(todayReturn.getNumber().compareTo(yesterdayReturn.getNumber()) > 0 ? "up" : "down")
                .returnRate((returnRate.setScale(2,BigDecimal.ROUND_UP)) + "%")
                .returnRatePercent((BigDecimal.ZERO.compareTo(returnRateYesterday) != 0 ? ((returnRate.subtract(returnRateYesterday)).divide(returnRateYesterday, 2, RoundingMode.HALF_UP).abs()) : 0) + "%")
                .returnRateFlag(returnRate.compareTo(returnRateYesterday) > 0 ? "up" : "down")
                .build();

        return CommonResult.success(productSalesDataResponse);
    }

    public CommonResult statisticalByTopCategory(SalesStatisticalRequest request) {
        if (null != request.getStartTime()) {
            Date dNow = new Date(); //当前时间
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(dNow);//把当前时间赋给日历
            calendar.add(calendar.MONTH, -2); //设置为前2月
            Date dBefore = calendar.getTime();
            if (request.getStartTime().getTime() < dBefore.getTime()) {
                request.setStartTime(dBefore);
            }
        }else {
            if (null == request.getStartTime() && StringUtils.isBlank(request.getQueryTime())){
                request.setQueryTime("today");
            }
        }
        if (StringUtils.isBlank(request.getQueryTime())) {
            request.setQueryTime(null);
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        //一级分类id/一级分类名称/销量/销售金额
        List<ProductComputeVO> saleOrders = ordersMapper.getStatisticalByTopCategory(request);
        List<Integer> categoryIds = saleOrders.stream().map(ProductComputeVO::getId).collect(Collectors.toList());
        List<TopCategorySalesStatisticalResponse> responses = new ArrayList<>();
        if (CollectionUtils.isEmpty(categoryIds)) {
            return CommonResult.success(CommonPage.restPage(responses));
        }
        request.setTopCategoryIds(categoryIds);
        //一级分类id/退货数量/退货金额
        List<ProductComputeVO> saleReturns = returnGoodsMapper.getStatisticalByTopCategory(request);
        //一级分类id/退货成功数量/退货成功金额
        List<ProductComputeVO> saleReturnsSuccess = returnGoodsMapper.getReturnSuccessByTopCategory(request);
        CommonPage productComputeVOCommonPage = CommonPage.restPage(saleOrders);
        saleOrders.stream().forEach(saleOrder -> {
            List<ProductComputeVO> collect = saleReturns.stream().filter(item -> item.getId().equals(saleOrder.getId())).collect(Collectors.toList());
            BigDecimal returnNum = BigDecimal.ZERO;
            BigDecimal returnMoney = BigDecimal.ZERO;
            BigDecimal returnRate = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(collect)) {
                returnNum = collect.get(0).getNumber();
                returnMoney = collect.get(0).getMoney();
                returnRate = collect.get(0).getNumber().divide(saleOrder.getNumber(), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            BigDecimal returnSuccessNum = BigDecimal.ZERO;
            List<ProductComputeVO> collect1 = saleReturnsSuccess.stream().filter(item -> item.getId().equals(saleOrder.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect1)) {
                returnSuccessNum = collect1.get(0).getNumber();
            }
            TopCategorySalesStatisticalResponse response = TopCategorySalesStatisticalResponse.builder()
                    .topCategoryTitle(saleOrder.getName())
                    .saleNum(saleOrder.getNumber().toString())
                    .saleMoney(saleOrder.getMoney().toString())
                    .returnNum(returnNum.toString())
                    .returnMoney(returnMoney.toString())
                    .returnSuccessNum(returnSuccessNum.toString())
                    .returnRate(returnRate.setScale(0, RoundingMode.HALF_UP) + "%")
                    .build();
            responses.add(response);
        });
        productComputeVOCommonPage.setList(responses);
        return CommonResult.success(productComputeVOCommonPage);
    }

    public CommonResult statisticalByProduct(SalesStatisticalRequest request) {
        if (null != request.getStartTime()) {
            Date dNow = new Date(); //当前时间
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(dNow);//把当前时间赋给日历
            calendar.add(calendar.MONTH, -2); //设置为前2月
            Date dBefore = calendar.getTime();
            if (request.getStartTime().getTime() < dBefore.getTime()) {
                request.setStartTime(dBefore);
            }
        }else {
            if (null == request.getStartTime() && StringUtils.isBlank(request.getQueryTime())){
                request.setQueryTime("today");
            }
        }
        if (StringUtils.isBlank(request.getQueryTime())) {
            request.setQueryTime(null);
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        //商品id/商品名称/销量/销售金额/供应商id/商品状态
        List<ProductComputeVO> saleOrders = ordersMapper.getStatisticalByProduct(request);
        List<Integer> productIds = saleOrders.stream().map(ProductComputeVO::getId).collect(Collectors.toList());

        List<ProductSalesStatisticalResponse> responses = new ArrayList<>();
        if (CollectionUtils.isEmpty(productIds)) {
            return CommonResult.success(CommonPage.restPage(responses));
        }
        List<Integer> bankerIds = saleOrders.stream().map(ProductComputeVO::getBankerId).collect(Collectors.toList());
        List<YxBanker> bankerList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bankerIds)) {
            bankerList = bankerMapper.selectByIds(bankerIds);
        }
        request.setProductIds(productIds);
        //商品id/退货数量/退货金额
        List<ProductComputeVO> saleReturns = returnGoodsMapper.getReturnByProduct(request);
        //商品id/退货成功数量/退货成功金额
        List<ProductComputeVO> saleReturnsSuccess = returnGoodsMapper.getReturnSuccessByProduct(request);
        List<YxBanker> finalBankerList = bankerList;
        CommonPage productComputeVOCommonPage = CommonPage.restPage(saleOrders);
        saleOrders.stream().forEach(saleOrder -> {
            List<ProductComputeVO> collect = saleReturns.stream().filter(item -> item.getId().equals(saleOrder.getId())).collect(Collectors.toList());
            BigDecimal returnNum = BigDecimal.ZERO;
            BigDecimal returnMoney = BigDecimal.ZERO;
            BigDecimal returnRate = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(collect)) {
                returnNum = collect.get(0).getNumber();
                returnMoney = collect.get(0).getMoney();
                returnRate = collect.get(0).getNumber().divide(saleOrder.getNumber(), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            BigDecimal returnSuccessNum = BigDecimal.ZERO;
            List<ProductComputeVO> collect1 = saleReturnsSuccess.stream().filter(item -> item.getId().equals(saleOrder.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect1)) {
                returnSuccessNum = collect1.get(0).getNumber();
            }
            List<YxBanker> collect2 = finalBankerList.stream().filter(item -> item.getId().equals(saleOrder.getBankerId())).collect(Collectors.toList());
            String bankerName = "";
            String buyer = "";
            if (!CollectionUtils.isEmpty(collect2)) {
                bankerName = collect2.get(0).getName();
                buyer = collect2.get(0).getBuyer();
            }
            ProductSalesStatisticalResponse response = ProductSalesStatisticalResponse.builder()
                    .id(saleOrder.getId())
                    .bankerName(bankerName)
                    .productName(saleOrder.getName())
                    .saleNum(saleOrder.getNumber().toString())
                    .saleMoney((null != saleOrder.getMoney() ? saleOrder.getMoney() : 0).toString())
                    .returnNum(returnNum.toString())
                    .returnMoney(returnMoney.toString())
                    .returnSuccessNum(returnSuccessNum.toString())
                    .returnRate(returnRate.setScale(0, RoundingMode.HALF_UP) + "%")
                    .status(saleOrder.getStatus())
                    .buyer(buyer)
                    .build();
            responses.add(response);
        });
        productComputeVOCommonPage.setList(responses);
        return CommonResult.success(productComputeVOCommonPage);
    }
}
